<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <a-form size="small" :model="pageData.queryData" layout="inline">
          <a-form-item label="日期">
            <a-range-picker  popup-container="html" 
              :style="{ width: '300px' }"
              class="bacClass"
              v-model="pageData.queryData.createTimeArr"
            />
          </a-form-item>
          <a-form-item label="流转卡号">
            <a-input
              @press-enter="selectHandler"
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="pageData.queryData.flowCardCode"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="['查询', '导出']" @export="exports" @select="selectHandler"> </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: calc(100% - 45px)"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        :suppressRowClickSelection="true"
      ></AgGridVuesCopys>
    </template>

    <!-- <paginationCopys :page-size="pagination.pageSize" :current="pagination.page" :total="pagination.total" show-total show-jumper
            show-page-size @change="nextDoRefreshPage" @page-size-change="nextDoRefreshSize" style="justify-content: center" /> -->
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import { useTable, usePagination, useTableColumn } from '@/hooks/table'

  import { ref, reactive, onMounted } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import 'ag-grid-community/styles/ag-grid.css'
  import 'ag-grid-community/styles/ag-theme-alpine.css'
  import { localeText } from '@/api/aggridZw'
  
  import { Message, Modal } from '@arco-design/web-vue'

  interface paramData {
    id: any
    examineItem: string | undefined
    minRange: string | undefined
    maxRange: string | undefined
    choosableValue: string | undefined
    defectScore: string | undefined
    chooseScore: string | undefined
    remark: string | undefined
  }

  export default {
    //成检验布登记报表
    name: 'ChenGJianData',
    setup() {
      //隐藏显示头部
      const headerShow = ref<boolean>(true)
      const pageData = reactive<{
        pageLoading: boolean
        labelColFlex: string
        queryData: any
      }>({
        pageLoading: false,
        labelColFlex: '120px',
        queryData: {
          createTimeArr: [],
          flowCardCode: '',
        },
      })
      //查询列表
      onMounted(() => {
        selectHandler()
      })

      //切换分页
      const nextDoRefreshPage = (val: any) => {
        pagination.page = val
        doRefresh()
      }
      const nextDoRefreshSize = (val: any) => {
        pagination.pageSize = val
        doRefresh()
      }
      const pagination = usePagination(doRefresh)
      const table = useTable()
      function doRefresh() {
        pageData.pageLoading = true
        if (pageData.queryData.createTimeArr == undefined) {
          pageData.queryData.createTimeArr = []
        }
        post({
          url: 'dwQms/FinishedInspection/getCloth',
          data: {
            flowCardCode: pageData.queryData.flowCardCode,
            startDate: pageData.queryData.createTimeArr[0],
            endDate: pageData.queryData.createTimeArr[1],
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data)
              pagination.setTotalSize(0)
              gridOption.value.setRowData(data)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }

      // 表格准备事件
      const tableColumns = useTableColumn([
        {
          title: '流转卡号',
          key: 'flowCardCode',
          dataIndex: 'flowCardCode',
        },
        {
          title: '布种',
          key: 'greyType',
          dataIndex: 'greyType',
        },
        {
          title: '布票号',
          key: 'clothCode',
          dataIndex: 'clothCode',
        },
        {
          title: '原重量（KG）',
          key: 'finishedWeight',
          dataIndex: 'finishedWeight',
        },
        {
          title: '原匹数',
          key: 'houseNum',
          dataIndex: 'houseNum',
        },
        {
          title: '异常重量(KG)',
          key: 'finishedWeightAnomaly',
          dataIndex: 'finishedWeightAnomaly',
        },
        {
          title: '异常匹数',
          key: 'anomalyHouseNum',
          dataIndex: 'anomalyHouseNum',
        },
        {
          title: '验布匹号',
          key: 'houseNum',
          dataIndex: 'houseNum',
        },

        {
          title: '匹号重量(KG)',
          key: 'flowCardWeight',
          dataIndex: 'flowCardWeight',
        },
        {
          title: '不良率(%)',
          key: 'rejectRatio',
          dataIndex: 'rejectRatio',
        },
        {
          title: '疵点分数',
          key: 'deductMarks',
          dataIndex: 'deductMarks',
        },
        {
          title: '验布状态',
          key: 'checkResult',
          dataIndex: 'checkResult',
          cellRenderer: {
            template: `
                  <el-tag type="success" v-if="states == 0">OK</el-tag>
                  <el-tag type="danger"  v-if="states == 1">不OK</el-tag>
                  `,
            setup(props: any) {
              return {
                states: props.params.data.checkResult,
              }
            },
          },
        },
        {
          title: '回修部门',
          key: 'returnRepairs',
          dataIndex: 'returnRepairs',
        },
        {
          title: '是否对色',
          key: 'coloringMatch',
          dataIndex: 'coloringMatch',
          cellRenderer: {
            template: `
                  <el-tag type="success" v-if="states == 0">是</el-tag>
                  <el-tag type="danger"  v-if="states == 1">否</el-tag>
                  `,
            setup(props: any) {
              return {
                states: props.params.data.coloringMatch,
              }
            },
          },
        },
        {
          title: '对色状态',
          key: ' coloringState',
          dataIndex: 'coloringState',
          cellRenderer: {
            template: `
                  <el-tag type="success" v-if="states == 1">是</el-tag>
                  <el-tag type="danger"  v-if="states == 0">否</el-tag>
                  `,
            setup(props: any) {
              return {
                states: props.params.data.coloringState,
              }
            },
          },
        },
        {
          title: '是否开方',
          key: ' extractionState',
          dataIndex: 'extractionState',
          cellRenderer: {
            template: `
                  <el-tag type="success" v-if="states == 0">是</el-tag>
                  <el-tag type="danger"  v-if="states == 1">否</el-tag>
                  `,
            setup(props: any) {
              return {
                states: props.params.data.extractionState,
              }
            },
          },
        },

        {
          title: '验布状态',
          key: 'Chubb',
          dataIndex: 'Chubb',
          cellRenderer: {
            template: `
                  <el-tag type="success" v-if="states == 0">完结</el-tag>
                  <el-tag type="danger"  v-if="states == 1">未完结</el-tag>
                  `,
            setup(props: any) {
              return {
                states: props.params.data.Chubb,
              }
            },
          },
        },
      ])
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: o.width,
          cellRenderer: o.cellRenderer,
        }
        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const localeText1: any = ref(localeText)

      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          //拼接表头
          let head = ''
          let nowRow: any = gridOption.value.getSelectedRows()
          tableColumns.forEach(function (o) {
            head += '<th>' + o['title'] + '</th>'
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr>'
            tableColumns.forEach(function (o1) {
              let key = o1['key']
              var value = o[key]
              if (value != undefined) {
                body += '<td>' + o[key] + '</td>'
              } else {
                body += '<td></td>'
              }
            })
            body += '</tr>'
          })
          tableToXlsx(head, '成检验布登记报表', body)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }
      return {
        pagination,
        table,
        pageData,
        selectHandler,
        headerShow,
        nextDoRefreshPage,
        nextDoRefreshSize,
        defaultColDef,
        localeText1,
        tc,
        gridReady,
        gridOption,
        exports,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
